using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SOEI.Solution.Customized;
using SOEI.Solution.DomainEntities.Organization.DomainService;
using SOEI.Solution.DomainEntities.Organization.Dtos;
using SOEI.Solution.Integratedes.Organization;
using SOEI.Solution.Integratedes.Organization.DomainService;
using SOEI.Solution.Integratedes.Organization.Dtos;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace SOEI.Solution.DomainEntities.Organization
{
    /// <summary>
    /// 【扩展模块】  <br/>
    /// 【功能描述】  ：经济机构 模块<br/>
    /// 【创建日期】  ：2020.05.21 <br/>
    /// 【开发人员】  ：static残影<br/>
    ///</summary>
    [AbpAuthorize]
    [ApiExplorerSettings(GroupName = "Manager", IgnoreApi = false)]
    public class EconomyOrganiAppService : SolutionAppServiceBase, IEconomyOrganiAppService
    {
        /// <summary>
        ///【EconomyOrgani】仓储层
        /// </summary>
        private readonly IRepository<EconomyOrgani, long> _economyorganiRepository;

        /// <summary>
        ///【EconomyOrgani】领域服务
        /// </summary>
        private readonly IEconomyOrganiManager _economyorganiManager;

        // 综合系统 机构领域服务
        private readonly IOEconomyOrganiManager _oeconomyOrganiManager;

        /// <summary>
        ///【OrganiPerson】领域服务
        /// </summary>
        private readonly IOrganiPersonManager _organipersonManager;

        public EconomyOrganiAppService(
            IRepository<EconomyOrgani, long> economyorganiRepository,
            IEconomyOrganiManager economyorganiManager,
            IOrganiPersonManager organipersonManager,
            IOEconomyOrganiManager oeconomyOrganiManager
        )
        {
            _economyorganiRepository = economyorganiRepository;
            _economyorganiManager = economyorganiManager;
            _organipersonManager = organipersonManager;
            _oeconomyOrganiManager = oeconomyOrganiManager;
        }

        #region -------------------------------------------------辅助工具生成---------------------------------------------- 

        /// <summary>
        ///【EconomyOrgani】获取的分页列表信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        public async Task<PagedResultDto<EconomyOrganiListDto>> GetPaged(GetEconomyOrganisInput input)
        {
            var query = _economyorganiRepository.GetAll()
                          //模糊搜索 字段JGBH
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.JGBH.Contains(input.FilterText))
                          //模糊搜索 字段DZ
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.DZ.Contains(input.FilterText))
                          //模糊搜索 字段ZGBM
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.ZGBM.Contains(input.FilterText))
                          //模糊搜索 字段ZCZJ
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.ZCZJ.Contains(input.FilterText))
                          //模糊搜索 字段FRXM
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.FRXM.Contains(input.FilterText))
                          //模糊搜索 字段FRDH
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.FRDH.Contains(input.FilterText))
                          //模糊搜索 字段LXRXM
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.LXRXM.Contains(input.FilterText))
                          //模糊搜索 字段LXRDH
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.LXRDH.Contains(input.FilterText))
                          //模糊搜索 字段YWLXDH
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.YWLXDH.Contains(input.FilterText))
                          //模糊搜索 字段YZBH
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.YZBH.Contains(input.FilterText))
                          //模糊搜索 字段YYZZH
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.YYZZH.Contains(input.FilterText))
                          //模糊搜索 字段SWDJZH
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.SWDJZH.Contains(input.FilterText))
                          //模糊搜索 字段FRDMZH
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.FRDMZH.Contains(input.FilterText))
                          //模糊搜索 字段YWFW
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.YWFW.Contains(input.FilterText))
                          //模糊搜索 字段ZJLY
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.ZJLY.Contains(input.FilterText))
                          //模糊搜索 字段JGLXDM
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.JGLXDM.Contains(input.FilterText))
                          //模糊搜索 字段SJDW
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.SJDW.Contains(input.FilterText))
                          //模糊搜索 字段FZRXM
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.FZRXM.Contains(input.FilterText))
                          //模糊搜索 字段FZRDH
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.FZRDH.Contains(input.FilterText))
                          //模糊搜索 字段JJXZDM
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.JJXZDM.Contains(input.FilterText))
                          //模糊搜索 字段LRSJ
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.LRSJ.Contains(input.FilterText))
                          //模糊搜索 字段JGZT
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.JGZT.Contains(input.FilterText))
                          //模糊搜索 字段GLYBH
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.GLYBH.Contains(input.FilterText))
                          //模糊搜索 字段ZCDZ
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.ZCDZ.Contains(input.FilterText))
                          //模糊搜索 字段ZCDZYB
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.ZCDZYB.Contains(input.FilterText))
                          //模糊搜索 字段BGCSDM
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.BGCSDM.Contains(input.FilterText))
                          //模糊搜索 字段KZJQDMMHTBH
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.KZJQDMMHTBH.Contains(input.FilterText))
                          //模糊搜索 字段JJHTJYBH
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.JJHTJYBH.Contains(input.FilterText))
                          //模糊搜索 字段JYGPXXBH
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.JYGPXXBH.Contains(input.FilterText))
                          //模糊搜索 字段EMAIL
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.EMAIL.Contains(input.FilterText))
                          //模糊搜索 字段QQ
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.QQ.Contains(input.FilterText))
                          //模糊搜索 字段NJYQSJ
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.NJYQSJ.Contains(input.FilterText))
                          //模糊搜索 字段SFFZJG
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.SFFZJG.Contains(input.FilterText))
                          //模糊搜索 字段ZGS
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.ZGS.Contains(input.FilterText))
                          //模糊搜索 字段YZGSGX
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.YZGSGX.Contains(input.FilterText))
                          //模糊搜索 字段PYJC
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.PYJC.Contains(input.FilterText))
                          //模糊搜索 字段JGZP
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.JGZP.Contains(input.FilterText))
                          //模糊搜索 字段KWQ
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.KWQ.Contains(input.FilterText))
                          //模糊搜索 字段JGMC
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.JGMC.Contains(input.FilterText))
                          //模糊搜索 字段SFYQ
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.SFYQ.Contains(input.FilterText))
                          //模糊搜索 字段ZGSJGBH
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.ZGSJGBH.Contains(input.FilterText))
                          //模糊搜索 字段FRZJLX
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.FRZJLX.Contains(input.FilterText))
                          //模糊搜索 字段FRZJHM
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.FRZJHM.Contains(input.FilterText))
                          //模糊搜索 字段JGQC
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.JGQC.Contains(input.FilterText))
                          //模糊搜索 字段SFGTGSH
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.SFGTGSH.Contains(input.FilterText))
            ;
            // TODO:根据传入的参数添加过滤条件

            var count = await query.CountAsync();

            var entityList = await query
                    .OrderBy(input.Sorting).AsNoTracking()
                    .PageBy(input)
                    .ToListAsync();

            var entityListDtos = ObjectMapper.Map<List<EconomyOrganiListDto>>(entityList);

            return new PagedResultDto<EconomyOrganiListDto>(count, entityListDtos);
        }

        /// <summary>
        ///【EconomyOrgani】通过指定id获取MemberListDto信息
        /// </summary>

        public async Task<EconomyOrganiListDto> GetById(EntityDto<long> input)
        {
            var entity = await _economyorganiRepository.GetAsync(input.Id);

            var dto = ObjectMapper.Map<EconomyOrganiListDto>(entity);
            return dto;
        }

        /// <summary>
        ///【EconomyOrgani】 获取编辑
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<GetEconomyOrganiForEditOutput> GetForEdit(NullableIdDto<long> input)
        {
            var output = new GetEconomyOrganiForEditOutput();
            EconomyOrganiEditDto editDto;

            if (input.Id.HasValue)
            {
                var entity = await _economyorganiRepository.GetAsync(input.Id.Value);
                editDto = ObjectMapper.Map<EconomyOrganiEditDto>(entity);
            }
            else
            {
                editDto = new EconomyOrganiEditDto();

            }
            output.EconomyOrgani = editDto;
            return output;
        }
        /// <summary>
        ///【EconomyOrgani】 添加或者修改的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        public async Task CreateOrUpdate(CreateOrUpdateEconomyOrganiInput input)
        {

            if (input.EconomyOrgani.Id.HasValue)
            {
                await Update(input.EconomyOrgani);
            }
            else
            {
                await Create(input.EconomyOrgani);
            }
        }
        /// <summary>
        ///【EconomyOrgani】新增
        /// </summary>

        protected virtual async Task<EconomyOrganiEditDto> Create(EconomyOrganiEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = ObjectMapper.Map<EconomyOrgani>(input);
            //调用领域服务
            entity = await _economyorganiManager.CreateAsync(entity);

            var dto = ObjectMapper.Map<EconomyOrganiEditDto>(entity);
            return dto;
        }

        /// <summary>
        ///【EconomyOrgani】编辑
        /// </summary>

        protected virtual async Task Update(EconomyOrganiEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新
            var key = input.Id.Value;
            var entity = await _economyorganiManager.GetEntityByIdAsync(key);
            //  input.MapTo(entity);
            //将input属性的值赋值到entity中
            ObjectMapper.Map(input, entity);
            await _economyorganiManager.UpdateAsync(entity);
        }

        /// <summary>
        ///【EconomyOrgani】删除信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        public async Task Delete(EntityDto<long> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _economyorganiManager.DeleteAsync(input.Id);
        }

        /// <summary>
        ///【EconomyOrgani】 批量删除Member的方法
        /// </summary>

        public async Task BatchDelete(List<long> input)
        {
            // TODO:批量删除前的逻辑判断，是否允许删除
            await _economyorganiManager.BatchDelete(input);
        }

        #endregion

        #region -------------------------------------------------用户自定义------------------------------------------------
        /*请在此扩展应用服务实现*/

        /// <summary>
        ///【EconomyOrgani】获取我的机构信息（必须有当前登录的用户，如果是Admin登录没有机构信息则返回一个空的机构）
        /// </summary>
        /// <param></param>
        /// <returns></returns>
        public async Task<OEconomyOrganiListDto> GetOwenOrgani()
        {
            // 1. 获取当前登录的用户信息（）
            var userEntity = await this.GetPersonChecker();

            //2. 判断当前登录 是否经济机构用户

            var orgniEntity = await this._oeconomyOrganiManager.GetEntityByIdAsync(userEntity.OriginalNumber);

            if (orgniEntity == null)
            {
                orgniEntity = new OEconomyOrgani();
                orgniEntity.JGZT = ((int)EApprovalStatus.WaitSubmit).ToString();
                orgniEntity.JGZTMC = "待提交";
            }

            // 我的机构初始化默认字段
            orgniEntity.KZJQDMMHTBH = "02"; // 买卖合同签订编号
            orgniEntity.JJHTJYBH = "02"; // 经纪合同效验编号
            orgniEntity.JYGPXXBH = "02"; // 校验挂牌信息编号
            orgniEntity.KWQ = "0"; // 可网签
            orgniEntity.SFGTGSH = string.Empty; // 是否个体工商户
            orgniEntity.SFYQ = string.Empty; // 是否网签
                                             // 默认字段以后需要补全
            var dto = ObjectMapper.Map<OEconomyOrganiListDto>(orgniEntity);
            return dto;
        }

        /// <summary>
        ///【EconomyOrgani】获取我的备案信息
        /// </summary>
        /// <param></param>
        /// <returns></returns>
        public async Task<OEconomyOrganiListDto> GetOwenOrganiRecord()
        {
            // 1. 获取当前登录的用户信息（）
            var userEntity = await this.GetPersonChecker();
            // 2. 获取Zhxt机构信息
            var orgniEntity = await this._oeconomyOrganiManager.GetEntityByIdAsync(userEntity.OriginalNumber);

            if (orgniEntity == null)
            {
                orgniEntity = new OEconomyOrgani();
                orgniEntity.JGZT = ((int)EApprovalStatus.WaitSubmit).ToString();
                orgniEntity.JGZTMC = "待提交";
            }

            // 我的机构初始化默认字段
            orgniEntity.KZJQDMMHTBH = "02"; // 买卖合同签订编号
            orgniEntity.JJHTJYBH = "02"; // 经纪合同效验编号
            orgniEntity.JYGPXXBH = "02"; // 校验挂牌信息编号
            orgniEntity.KWQ = "0"; // 可网签
            orgniEntity.SFGTGSH = string.Empty; // 是否个体工商户
            orgniEntity.SFYQ = string.Empty; // 是否网签
                                             // 默认字段以后需要补全
            var dto = ObjectMapper.Map<OEconomyOrganiListDto>(orgniEntity);
            return dto;
        }

        /// <summary>
        ///【EconomyOrgani】 提交备案数据(临时保存)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        // [AbpAuthorize(EconomyOrganiPermissions.Node)]
        public async Task OwenUpdate(OEconomyOrganiEditDto input)
        {
            var userEntity = await this.GetPersonChecker();

            if (!string.IsNullOrEmpty(input.Id))
            {
                //TODO:更新前的逻辑判断，是否允许更新
                var entity = await _oeconomyOrganiManager.GetEntityByIdAsync(input.Id);
                //将input属性的值赋值到entity中
                ObjectMapper.Map(input, entity);
                await _oeconomyOrganiManager.UpdateAsync(entity);
            }
            else
            {
                await this.CreateOrganization(userEntity.OriginalNumber);
            }

        }

        /*请在此扩展应用服务实现*/

        /// <summary>
        ///【OrganiPerson】 提交初始化备案
        /// </summary>
        public async Task SubmitApproval()
        {
            // 1. 获取当前登录的用户信息（）
            var userEntity = await this.GetPersonChecker();
            // 2. 机构信息提交
            await _oeconomyOrganiManager.SubmitInitRecord(userEntity.OriginalNumber);
            // 3. 机构人员信息提交
            await _organipersonManager.SubmitApproval(userEntity.OrganizeID.Value);
            // 4. 处理数据同步（插入经济机构到综合系统）



        }
        #endregion

        #region  ----------------------------辅助方法-------------------------------

        /// <summary>
        /// 修改逻辑后为了对应之前的数据不存zhxt的账户，默认添加一个新的
        /// </summary>
        protected async Task<OEconomyOrgani> CreateOrganization(string OriginalNumber)
        {
            var entity = new OEconomyOrgani()
            {
                // StateCode = EOrgStateCode.NewRegistration, // 设置为新注册的机构

                // 综合系统中的机构编号
                Id = OriginalNumber,
                // 买卖合同签订编号
                KZJQDMMHTBH = "02",
                // 经纪合同效验编号
                JJHTJYBH = "02",
                // 校验挂牌信息编号
                JYGPXXBH = "01",
                // 可网签
                KWQ = "0",
                // 是否个体工商户
                SFGTGSH = string.Empty,
                // 是否网签  
                SFYQ = string.Empty,
                // 设置机构状态为待提交
                JGZT = ((int)EApprovalStatus.WaitSubmit).ToString()
            };
            await this._oeconomyOrganiManager.CreateAsync(entity);
            return entity;
        }
        #endregion
    }
}
